import comTitle from "@/views/com/com_title.vue";
import { addObj, putObj, getObj } from '@/api/shop/shop/list.js'
// import BMap from "BMap";
import VDistpicker from 'v-distpicker'

export default {
    components: {
        comTitle,
        VDistpicker
    },
    data() {
        return {
            value: "",
            address_detail: null,
            userlocation: { lng: "", lat: "" },
            labelWidth: "120px",
            disabled: false,
            ruleForm: {
                yewu: [],
                businessType: [],
                deliveryXiaoQu: [{ communityNames: '' }]
            },
            rules: {
                shopName: [{ required: true, message: '请输入门店名称', trigger: 'blur' }],
                gysdz: [{ required: true, message: '请选择门店区域', trigger: 'change' }],
                shopType: [{ required: true, message: '请选择门店归属', trigger: 'change' }],
                businessType: [{ required: true, message: '请选择所属业务', trigger: 'change' }],
                longitude: [{ required: true, message: '请确认获取经维度', trigger: 'change' }],
                latitude: [{ required: true, message: '请确认获取经维度', trigger: 'change' }],
            },
            adress: [  //地址
            ],
            mdguishuList: [ //门店归属
                {
                    value: '01',
                    label: "平台",
                },
                {
                    value: '02',
                    label: "分公司",
                }, {
                    value: '03',
                    label: "代理商",
                }
            ],
            yewuList: this.$store.getters.businessTypeList,
            loading: false,
        }
    },
    mounted() {
        this.getList()
        this.initMap()
    },

    methods: {
        initMap() {
            var longitude = this.$route.query.longitude
            var latitude = this.$route.query.latitude
            //定义工厂模式函数
            var marker, info, citylocation, searchService, ap, geocoder;
            var center = new qq.maps.LatLng(latitude ? latitude : 39.916527, longitude ? longitude : 116.397128);
            geocoder = new qq.maps.Geocoder();  //显示地图地址信息
            ap = new qq.maps.place.Autocomplete(document.getElementById('suggestId'));

            var myOptions = {
                zoom: 13,               //设置地图缩放级别
                center: center,      //设置中心点样式
                // mapTypeId: qq.maps.MapTypeId.ROADMAP  //设置地图样式详情参见MapType
            }
            var map = new qq.maps.Map(document.getElementById("all-map"), myOptions);


            //调用Poi检索类。用于进行本地检索、周边检索等服务。
            searchService = new qq.maps.SearchService({
                map: map
            });

            if (!longitude && !latitude) {  //默认定位
                citylocation = new qq.maps.CityService({
                    //请求成功回调函数
                    complete: function (result) {
                        map.setCenter(result.detail.latLng);
                    },
                    error: function () {
                        alert("出错了，请输入正确的经纬度！！！");
                    }
                });
                citylocation.searchLocalCity();
            }


            info = new qq.maps.InfoWindow({
                map: map,
                position: center,
            });

            geocoder.setComplete((result) => {
                info.open();
                info.setContent('<div style="width:280px;min-height:50px">' +
                    result.detail.address + '</div>');
                info.setPosition(result.detail.location);
                console.log(result)
                this.ruleForm.provinceCode = result.detail.addressComponents.province
                this.ruleForm.cityCode = result.detail.addressComponents.city
                this.ruleForm.districtCode = result.detail.addressComponents.district
                this.ruleForm.address = result.detail.address
                this.ruleForm.longitude = result.detail.location.lng;
                this.ruleForm.latitude = result.detail.location.lat;
                this.address_detail = result.detail.address
            })

            marker = new qq.maps.Marker({
                position: center,
                map: map
            });
            //添加监听事件  获取鼠标点击事件
            qq.maps.event.addListener(map, 'click', (event) => {
                console.log(event.latLng)
                geocoder.getAddress(event.latLng)  //显示地图地址信息
                marker.setPosition(event.latLng);

            });

            qq.maps.event.addListener(ap, "confirm", (res) => {
                this.ruleForm.longitude = undefined
                this.ruleForm.latitude = undefined
                geocoder.getLocation(res.value);
                //若服务请求失败，则运行以下函数
                geocoder.setError(function () {  //搜索失败按周边搜索
                    searchService.search(res.value);
                });
            })

            if (this.$route.query.id) {  //回显
                info.open();
                info.setContent('<div style="width:280px;min-height:50px">' +
                    this.$route.query.address + '</div>')
            }
        },
        getList() {
            if (this.$route.query.id) {
                getObj(this.$route.query.id).then(val => {
                    var data = val.data.data
                    this.ruleForm = data
                    if (this.ruleForm.businessType) {
                        if (this.ruleForm.businessType.indexOf(',') > -1) {
                            this.ruleForm.businessType = this.ruleForm.businessType.split(',')
                        } else {
                            let list = []
                            list.push(this.ruleForm.businessType)
                            this.ruleForm.businessType = list
                        }
                    }
                    this.address_detail = this.ruleForm.address

                    let deliveryXiaoQu = []
                    if (this.ruleForm.communityNames.length) {
                        this.ruleForm.communityNames.forEach(item => {
                            deliveryXiaoQu.push({ communityNames: item })
                        })

                    } else {
                        deliveryXiaoQu = [{ communityNames: '' }]
                    }
                    this.$set(this.ruleForm, 'deliveryXiaoQu', deliveryXiaoQu)
                    console.log(this.ruleForm)
                })
            }


        },
        save() {   //保存
            console.log(this.ruleForm)
            let obj = { ...this.ruleForm }
            obj.status = '01'

            console.log(obj)
            this.$refs['ruleForm'].validate((valid) => {
                if (valid) {
                    if (this.ruleForm.provinceCode && this.ruleForm.cityCode && this.ruleForm.districtCode) {
                        this.loading = true

                        obj.businessType = obj.businessType.join(',')
                        let communityNames = []
                        obj.deliveryXiaoQu.forEach(item => {
                            communityNames.push(item.communityNames)
                        });
                        obj.communityNames = communityNames.join(',')

                        addObj(obj).then(() => {
                            this.$message.success('添加成功')
                            this.quxiao()
                            this.loading = false
                        }).catch(() => {
                            this.loading = false
                        })
                    } else {
                        this.$message.warning('请选择省市区')
                    }
                } else {
                    return false;
                }
            });
        },
        upDatasave() {
            let obj = { ...this.ruleForm }
            obj.status = '01'
            console.log(obj)
            this.$refs['ruleForm'].validate((valid) => {
                if (valid) {
                    this.loading = true

                    obj.businessType = obj.businessType.join(',')
                    let communityNames = []
                    obj.deliveryXiaoQu.forEach(item => {
                        communityNames.push(item.communityNames)
                    });
                    obj.communityNames = communityNames.join(',')


                    putObj(obj).then(() => {
                        this.$message.success('修改成功')
                        this.quxiao()
                        this.loading = false
                    }).catch(() => {
                        this.loading = false
                    })
                } else {
                    return false;
                }
            });
        },
        quxiao() {  //取消
            this.$router.go(-1)
            this.$refs['ruleForm'].resetFields();
            this.ruleForm = {
                yewu: [],
                businessType: [],
                deliveryXiaoQu: [{ communityNames: '' }]
            }
        },
        onSure() {
            this.ruleForm.longitude = this.userlocation.lng;
            this.ruleForm.latitude = this.userlocation.lat;
            this.ruleForm.address = this.address_detail
            console.log(this.ruleForm.longitude, this.ruleForm.latitude)
        },
        selected(data) {
            console.log(data)
            this.ruleForm.provinceCode = data.province.value
            this.ruleForm.cityCode = data.city.value
            this.ruleForm.districtCode = data.area.value
            // if (!this.$route.query.id) {
            //     this.address_detail = this.ruleForm.provinceCode + this.ruleForm.cityCode + this.ruleForm.districtCode
            // }
        },
        addKchs(item) {
            this.ruleForm.deliveryXiaoQu.push({ communityNames: '' })
            this.$forceUpdate()
        },
        editKchs(item) {
            let index = this.ruleForm.deliveryXiaoQu.indexOf(item);
            if (index !== -1) {
                this.ruleForm.deliveryXiaoQu.splice(index, 1);
            }
            this.$forceUpdate()
        },
    }

} 